<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="显示范围" prop="fullScreenIntervalCode">
          <el-select
            v-model="queryParams.fullScreenIntervalCode"
            placeholder="请选择显示范围"
            clearable
          >
            <el-option
              v-for="item in fullScreenPointList"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="TrendCharts" type="primary" @click="StartRunChart">开始曲线</el-button>
          <el-button icon="VideoPause" @click="StopChart">停止曲线</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card
      ><!-- 曲线 -->
      <el-row>
        <el-col :span="4">
          <el-tree-v2
            ref="treeRef"
            style="max-width: 300px"
            :data="devInfoTreeList"
            @check-change="handleCheckChange"
            show-checkbox
            :props="props"
            :height="620"
          />
        </el-col>
        <el-col :span="20">
          <div
            Id="chartId"
            ref="chartRef"
            style="width: 100%; height: 620px"
          ></div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { init } from "echarts";
import moment from "moment";
import { reactive, ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import {
  getVoDevBaseInfoTreeApi,
} from "@/api/devInfo/index";
import {
  getVoChartRealTime,
} from "@/api/trendchart/index";
import { Curve0, Curve1, Curve2, Curve3, Curve4, Curve5 } from "@/globalConf";
const treeRef = ref();
const isStopTimer = ref(false);
const starttime = ref();
const endtime = ref();
const nChartNum = ref();
const OrginChartDataResAr = ref([]);
const fullScreenPointList = ref([
  { name: "30s", value: 30 },
  { name: "1min", value: 60 },
  { name: "2min", value: 120 },
  { name: "5min", value: 300 },
  { name: "10min", value: 600 },
]);
const isClearChart = ref(false); //是否清除曲线
const timerChart = ref(); //曲线定时器,
const chartDateList = ref([]); //曲线时间周期
const chartDataList0 = ref([]); //曲线实时数据
const chartDataList1 = ref([]); //曲线实时数据
const chartDataList2 = ref([]); //曲线实时数据
const chartDataList3 = ref([]); //曲线实时数据
const chartDataList4 = ref([]); //曲线实时数据
const chartDataList5 = ref([]); //曲线实时数据
const props = {
  value: "id",
  label: "name",
  children: "devOneUnitPointInfoVoList",
  disabled: "disabled",
};
var barChart;
var option = {
  title: {
    text: "设备实时曲线",
  },
  tooltip: {
    trigger: "axis",
  },
  legend: {
    // data: ["Email"],
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  toolbox: {
    feature: {
      saveAsImage: {},
    },
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: chartDateList.value,
  },
  yAxis: {
    type: "value",
  },
  series: [],
};
const InitChartBasicConf = () => {
  option.series = [];

  selectedList.value?.forEach((ele, index) => {
    if (index == Curve0) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList0.value,
      });
    }
    if (index == Curve1) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList1.value,
      });
    }
    if (index == Curve2) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList2.value,
      });
    }
    if (index == Curve3) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList3.value,
      });
    }
    if (index == Curve4) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList4.value,
      });
    }
    if (index == Curve5) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList5.value,
      });
    }
  });
  
  myChart();
};
const StartRunChart = () => {
  StopChart();
  InitChartBasicConf();
  search();
  chartDateList.value = [];
  if (isClearChart.value) {
    chartDataList0.value = [];
    chartDataList1.value = [];
    chartDataList2.value = [];
    chartDataList3.value = [];
    chartDataList4.value = [];
    chartDataList5.value = [];
  }
  

  isStopTimer.value = false;

  timerChart.value = setInterval(() => {
    if (isStopTimer.value) {
      return;
    }

    starttime.value = moment().format("YYYY-MM-DD HH:mm:ss.SSS");

    if (nChartNum.value > 0 && OrginChartDataResAr.value.length > 0) {
      for (let index = 0; index < nChartNum.value; index++) {
        if (index == Curve0) {
          chartDateList.value.push(
            moment(OrginChartDataResAr.value[0].ts).format(
              "yyyy-MM-DD HH:mm:ss"
            )
          );
          chartDataList0.value.push(OrginChartDataResAr.value[index].vals);
          

          if (
            chartDataList0.value.length >
            queryParams.fullScreenIntervalCode - 1
          ) {
            // 计算需要删除的数量，并从索引 0 开始删除
            chartDateList.value.splice(
              0,
              chartDateList.value.length -
                queryParams.fullScreenIntervalCode +
                1
            );
            chartDataList0.value.splice(
              0,
              chartDataList0.value.length -
                queryParams.fullScreenIntervalCode +
                1
            );
          }
          option.series[0].data = chartDataList0.value;
          option.xAxis.data = chartDateList.value;
        }
        if (index == Curve1) {
          chartDataList1.value.push(OrginChartDataResAr.value[index].vals);
          if (
            chartDataList1.value.length >
            queryParams.fullScreenIntervalCode - 1
          ) {
            // 计算需要删除的数量，并从索引 0 开始删除
            chartDataList1.value.splice(
              0,
              chartDataList1.value.length -
                queryParams.fullScreenIntervalCode +
                1
            );
          }
          option.series[1].data = chartDataList1.value;
          option.xAxis.data = chartDateList.value;
        }
        if (index == Curve2) {
          chartDataList2.value.push(OrginChartDataResAr.value[index].vals);
          if (
            chartDataList2.value.length >
            queryParams.fullScreenIntervalCode - 1
          ) {
            // 计算需要删除的数量，并从索引 0 开始删除
            chartDataList2.value.splice(
              0,
              chartDataList2.value.length -
                queryParams.fullScreenIntervalCode +
                1
            );
          }
          option.series[2].data = chartDataList2.value;
          option.xAxis.data = chartDateList.value;
        }
        if (index == Curve3) {
          chartDataList3.value.push(OrginChartDataResAr.value[index].vals);
          if (
            chartDataList3.value.length >
            queryParams.fullScreenIntervalCode - 1
          ) {
            // 计算需要删除的数量，并从索引 0 开始删除
            chartDataList3.value.splice(
              0,
              chartDataList3.value.length -
                queryParams.fullScreenIntervalCode +
                1
            );
          }
          option.series[3].data = chartDataList3.value;
          option.xAxis.data = chartDateList.value;
        }
        if (index == Curve4) {
          chartDataList4.value.push(OrginChartDataResAr.value[index].vals);
          if (
            chartDataList4.value.length >
            queryParams.fullScreenIntervalCode - 1
          ) {
            // 计算需要删除的数量，并从索引 0 开始删除
            chartDataList4.value.splice(
              0,
              chartDataList4.value.length -
                queryParams.fullScreenIntervalCode +
                1
            );
          }
          option.series[4].data = chartDataList4.value;
          option.xAxis.data = chartDateList.value;
        }
        if (index == Curve5) {
          chartDataList5.value.push(OrginChartDataResAr.value[index].vals);
          if (
            chartDataList5.value.length >
            queryParams.fullScreenIntervalCode - 1
          ) {
            // 计算需要删除的数量，并从索引 0 开始删除
            chartDataList5.value.splice(
              0,
              chartDataList5.value.length -
                queryParams.fullScreenIntervalCode +
                1
            );
          }
          option.series[5].data = chartDataList5.value;
          option.xAxis.data = chartDateList.value;
        }
      }
    }
    getVoChartRealTimeByParams(historySelectedList.value); 
    barChart.clear   
    barChart.setOption(option);
    endtime.value = moment().format("YYYY-MM-DD HH:mm:ss");
  }, 1000);
  isClearChart.value = false;
};
const StopChart = () => {
  clearInterval(timerChart.value);
  timerChart.value = null;
  isStopTimer.value = true;
};
const devInfoTreeList = ref([]);
const queryParams = reactive({
  fullScreenIntervalCode: 30,
  devInfoCode: "",
  pointCode: "",
});
const myChart = () => { 
  barChart = init(document.getElementById("chartId"));
  barChart.showLoading();
  barChart.clear;
  barChart.setOption(option,{notMerge:true});
  window.onresize = barChart.resize;
};
//查询
const search = () => {
  nChartNum.value = selectedList.value.length;
  if (nChartNum.value <= 0) {
    return;
  }
  historySelectedList.value = selectedList.value.map((ele) => ({
    startTime: queryParams.startTime,
    endTime: queryParams.endTime,
    devPointValue: ele.id,
    devPointName: ele.name,
    tableName: ele.tableName,
  }));
  getVoChartRealTimeByParams(historySelectedList.value);
};

//曲线实时信息
const getVoChartRealTimeByParams = (data) => {
  getVoChartRealTime(data).then((res) => {
    OrginChartDataResAr.value = res.data;
    barChart.hideLoading();
  });
};
//获取EMS基本信息
const getVoDevBaseInfoTreeApiTree = () => {
  getVoDevBaseInfoTreeApi().then((res) => {
    devInfoTreeList.value = res.data;
  });
};
getVoDevBaseInfoTreeApiTree();
const selectedList = ref([]);
const historySelectedList = ref([]);
//树勾选事件
const handleCheckChange = (node, checked) => {
  if (checked) {
    // 当节点被选中时，将节点数据添加到列表
    selectedList.value.push({
      id: node?.id,
      name: node?.name,
      tableName: node?.devTableName,
    });
  } else {
    // 当节点被取消选中时，从列表中移除
    selectedList.value = selectedList.value.filter(
      (item) => item.id !== node.id
    );
  }
};
watch(
  selectedList,
  (newVal, oldVal) => {
    isClearChart.value = true;
  },
  {
    deep: true, // 如果需要深度监听内部变化
  }
);
nextTick(()=>{
  myChart();
})
onMounted(() => {
  
});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:deep(.dv-scroll-board .header) {
  background: #ddd !important;
}
:deep(.dv-scroll-board .rows .row-item) {
  background: gray !important;
}
</style>
